package com.fancon.android.gardenjokesx.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.utils.CheckValidate;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;

public class LoginActivity extends GardenJokesBaseActivity {
	
	private EditText username, password;
	private String inputUsername;
	private String inputPassword;
	private String registerID = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_login);
		SharedPreferences settings = getSharedPreferences(Constant.PREFS_REGISTER, 0);
		registerID = settings.getString(Constant.REGISTRATION_ID, "");
		Log.d("id", registerID);
		TextView title = (TextView) findViewById(R.id.action_bar_textview_title);
		title.setText(getText(R.string.login));
		username = (EditText)findViewById(R.id.username);
		password = (EditText)findViewById(R.id.password);
		View forgetPass = findViewById(R.id.forgot_password_link);
		forgetPass.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(), L02Activity.class);
				startActivity(intent);
			}
		});
		View login = findViewById(R.id.login_fragment_login_button);
		login.setOnClickListener(new android.view.View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Checkvalidate()) {
					// Request to server to loged in app
					JokesRequest loginRequest = new JokesRequest("login", LoginActivity.this);
					getGlobalState().getRequestQueue().addRequest(loginRequest);
				}
			}
		});
		
		View backBtn = findViewById(R.id.action_bar_button_back);
		backBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
	
	/**
	 * Check data validate
	 * 
	 * @return true or false
	 */
	public Boolean Checkvalidate() {
		inputUsername = this.username.getText().toString();
		inputPassword = this.password.getText().toString();
		
		// Check username
		if (inputUsername.length() == 0) {
			showErrorDialog(getString(R.string.ERR5001,getString(R.string.username)));
			username.requestFocus();
			return false;
		}
		if (inputUsername.length() > 16) {
			showErrorDialog(getString(R.string.ERR5003,getString(R.string.username), "16"));
			username.requestFocus();
			return false;
		}
		if (inputUsername.length() < 4) {
			showErrorDialog(getString(R.string.ERR5002,getString(R.string.username), "4"));
			username.requestFocus();
			return false;
		}
		if (!CheckValidate.checkAlphabetOrNumber(inputUsername)) {
			showErrorDialog(getString(R.string.ERR5004,getString(R.string.username)));
			username.requestFocus();
			return false;
		}
		// Check password
		if (inputPassword.length() == 0) {
			showErrorDialog(getString(R.string.ERR5001,getString(R.string.password)));
			password.requestFocus();
			return false;
		}
		if (inputPassword.length() > 16) {
			showErrorDialog(getString(R.string.ERR5003,getString(R.string.password),"16"));
			password.requestFocus();
			return false;
		}
		if (inputPassword.length() < 4) {
			showErrorDialog(getString(R.string.ERR5002,getString(R.string.password),"4"));
			password.requestFocus();
			return false;
		}
		if (!CheckValidate.checkAlphabetOrNumber(inputPassword)) {
			showErrorDialog(getString(R.string.ERR5004,getString(R.string.password)));
			password.requestFocus();
			return false;
		}
		
		
		return true;
	}
	
	/**
	 * Show dialog when validate is false
	 * 
	 * @param msg
	 */
	public void showErrorDialog(String msg) {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setCancelable(true)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
//						InputMethodManager inputManager = null;
//						 inputManager = (InputMethodManager)            
//								  SignupActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
//						 inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 1);
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	class JokesRequest extends RequestUI {
		private Activity context;
		private FanconProgressBar progress;
		private Boolean isFirst = true;
		String result = null;

		public JokesRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			context = activity;
			if (isFirst) {
				progress = FanconProgressBar.show(context,
						context.getString(R.string.loading));
			}
		}

		@Override
		public void execute() throws Exception {
			//Log.d("signup", execPost());
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("user_name",
					inputUsername));
			nameValuePairs.add(new BasicNameValuePair("password",
					StringUtil.md5(inputPassword)));
			nameValuePairs.add(new BasicNameValuePair("device_token", registerID));
			GardenJokesApiConnect apiConnect = new GardenJokesApiConnect(LoginActivity.this);
	    	result = apiConnect.execPost(LoginActivity.this, GardenJokesApiConnect.GROUP_L, "login", nameValuePairs);
	    	Log.d("login", result);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			if (result != null) {
				try {
					JSONObject jObject = new JSONObject(result);
					Boolean isSuccess = jObject.getBoolean("is_success");
					if (isSuccess) {
						// If success => remember to Preference and go to main Page
						String userId = jObject.getString("user_id");
						SharedPreferences settings = getSharedPreferences(
								Constant.PREFS_NAME, 0);
						SharedPreferences.Editor edit = settings.edit();
						edit.putString(Constant.USER_NAME, inputUsername);
						edit.putString(Constant.PASS, inputPassword);
//						edit.putString(Constant.URL_IMAGE,mUser.);
						edit.putString(Constant.USER_ID_LOGIN, userId);
						edit.putBoolean(Constant.IS_PRIVATE, jObject.getString("is_private").equals("0")?false:true);
						edit.commit();
						if(getIntent().getExtras() == null){
							Intent intent = new Intent(getApplicationContext(), GardenJokesActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							getApplicationContext().startActivity(intent);
						}else{
							String imagePath = getIntent().getExtras().getString(Constant.IMAGE_PATH);
							if(imagePath != null){
								Intent intent = new Intent(LoginActivity.this, P06Activity.class);
								intent.putExtra(Constant.IMAGE_PATH, imagePath);
								startActivity(intent);
							}
						}
						finish();
					} else {
						// If fail => show error dialog
						if (jObject.getString("message").equals("API-ERR-L0001")) {
							showErrorDialog("username or passwor invalid");
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			if (progress != null) {
				progress.dismiss();
			}
			
		}

	}
	
}
